﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Zatify.WebUI.Models.Account;
using Zatify.Domain.Abstract;
using Zatify.WebUI.Infrastructure.Absrtact;
using Zatify.Domain.Data;

namespace Zatify.WebUI.Controllers
{
    public class AccountController : Zatify.WebUI.Infrastructure.BaseController
    {
        private IZatifyRepository repository;
        private IZatifyAuthProvider authProvider;
        private IPasswordRecoveryService passwordRecoveryService;

        public AccountController(IZatifyRepository repository, IZatifyAuthProvider authProvider, IPasswordRecoveryService passwordRecoveryService)
        {
            this.repository = repository;
            this.authProvider = authProvider;
            this.passwordRecoveryService = passwordRecoveryService;
        }

        [HttpGet]
        [Utils.MyRequireHttps]
        public ActionResult Login(string returnUrl)
        {
            if (!String.IsNullOrEmpty(returnUrl))
            {
                if (returnUrl.Split('/').FirstOrDefault(x => String.Equals(x.ToLower(), "admin")) != null)
                    return RedirectToAction("Login", "Account", new { area = "Admin" });
            }

            return View(new LoginViewModel());
        }

        [HttpPost]
        [Utils.MyRequireHttps]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (this.ModelState.IsValid)
            {
                var loginUser = new User() { Login = model.UserID, Password = model.Password, RememberUser = model.RememberMe, TimeZoneOffset = model.TimeZoneOffset };

                if (this.authProvider.AuthenticateUser(loginUser))
                {
                    var redirectUrl = (!String.IsNullOrWhiteSpace(returnUrl) ? returnUrl : Url.Action("Promotions", "BusinessProfile"));

                    if (loginUser.UserRole == UserRole.RegularUser)
                        redirectUrl = (!String.IsNullOrWhiteSpace(returnUrl) ? returnUrl : Url.Action("Deals", "UserProfile"));

                    return Redirect(redirectUrl);
                }
                else
                {
                    this.ModelState.AddModelError("", "Incorrect user or password");
                    return View(model);
                }
            }

            return View(new LoginViewModel());
        }

        public ActionResult LogOff()
        {
            this.authProvider.LogOff();

            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult PasswordRecovery()
        {
            return View();
        }

        [HttpPost]
        public ActionResult PasswordRecovery(string email, string phone)
        {
            var userEmailExists = ((repository.Users.FirstOrDefault(u => u.Email == email) != null) || (repository.Businesses.FirstOrDefault(u => u.Email == email) != null));

            var userPhoneExists = ((repository.Users.FirstOrDefault(u => u.Phone == phone) != null) || (repository.Businesses.FirstOrDefault(u => u.CellPhone == phone) != null));

            var password = String.Empty;

            if (String.IsNullOrWhiteSpace(email) && String.IsNullOrWhiteSpace(phone))
            {
                this.ModelState.AddModelError("email_and_phone_empty_error", "Enter Email and/or Phone where to sent new password");
            }
            else if (!String.IsNullOrWhiteSpace(email) && !userEmailExists)
            {
                this.ModelState.AddModelError("Email", "Incorrect Email entered");
            }
            else if (!String.IsNullOrWhiteSpace(phone) && !userPhoneExists)
            {
                this.ModelState.AddModelError("Phone", "Incorrect Phone entered");
            }

            if (this.ModelState.IsValid)
            {
                SendPasswordRecovery(email, phone);

                return View("PasswordSended");
            }
            else
            {
                return View();
            }
        }

        private void SendPasswordRecovery(string email, string phone)
        {
            if (!String.IsNullOrWhiteSpace(phone))
            {
                var password = repository.Users.FirstOrDefault(u => u.Phone == phone) != null ? repository.Users.FirstOrDefault(u => u.Phone == phone).Password : String.Empty;

                if (String.IsNullOrWhiteSpace(password))
                    password = repository.Businesses.FirstOrDefault(u => u.CellPhone == phone) != null ? repository.Businesses.FirstOrDefault(u => u.CellPhone == phone).Password : String.Empty;

                passwordRecoveryService.SendPasswordRecoveryToMobile(password, phone);
            }

            if (!String.IsNullOrWhiteSpace(email))
            {
                var password = repository.Users.FirstOrDefault(u => u.Email == email) != null ? repository.Users.FirstOrDefault(u => u.Email == email).Password : String.Empty;

                if (String.IsNullOrWhiteSpace(password))
                    password = repository.Businesses.FirstOrDefault(u => u.Email == email) != null ? repository.Businesses.FirstOrDefault(u => u.Email == email).Password : String.Empty;

                passwordRecoveryService.SendPasswordRecoveryToEmail(password, email);
            }
        }
    }
}
